package com.jf.docsify.modules.system.login;

import org.apache.commons.lang3.StringUtils;

import com.jf.docsify.common.annotation.NotAuth;
import com.jf.docsify.common.utils.Resp;
import com.jf.docsify.common.utils.TokenUtil;
import com.jf.docsify.common.utils.WebUtil;
import com.jf.docsify.config.DocsifyConfig;
import com.jf.docsify.interceptor.AuthInterceptor;
import com.jf.docsify.modules.model.SysUser;
import com.jf.docsify.modules.system.user.UserService;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;

/**
 * Description: 登录控制层
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/26.1       chenwr    2022/7/26           Create
 * </pre>
 * @date 2022/7/26
 */
@Path("/admin")
public class LoginController extends Controller {

    @Inject
    UserService userService;

    @NotAuth
    @ActionKey("/admin/index")
    public void login() {
        setAttr("superAdmin", DocsifyConfig.superAdminUserName);
        render("index.html");
    }

    @NotAuth
    @ActionKey("/admin/login/do")
    public void doLogin() {
        String rawData = getRawData();
        SysUser user = JsonKit.parse(rawData, SysUser.class);
        SysUser sysUser = userService.find(user);
        String ipAddr = WebUtil.getIpAddr(getRequest());
        sysUser.setLoginIp(ipAddr);
        String jwtToken = TokenUtil.createJwtToken(String.valueOf(sysUser.getId()));
        jwtToken = TokenUtil.generateTokenInfo(jwtToken, sysUser);
        getResponse().setHeader(AuthInterceptor.JWT_KEY, jwtToken);
        Kv data = Kv.by("userId", sysUser.getId()).set("userName", sysUser.getUserName());
        Resp.success(data).done(this);
    }

    @NotAuth
    @ActionKey("/admin/validate/token")
    public void validateTk() {
        boolean isActive = false;
        Integer userId = null;
        String userName = null;
        String jwtToken = getHeader(AuthInterceptor.JWT_KEY);
        if (StringUtils.isNotBlank(jwtToken)) {
            SysUser user = TokenUtil.getUser(jwtToken);
            if (user != null) {
                isActive = TokenUtil.validateToken(String.valueOf(user.getId()), jwtToken);
                userId = user.getId();
                userName = user.getUserName();
            }
        }
        Kv data = Kv.by("isActive", isActive).set("userId", userId).set("userName", userName);
        Resp.success(data).done(this);
    }

    public void logout() {
        SysUser user = getAttr("user");
        if (user != null) {
            TokenUtil.removeToken(String.valueOf(user.getId()));
        }
        Resp.success().done(this);
    }
}